package day23;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 需求：编写一个聊天程序
 * 有接收数据的部分和发送数据的部分，并且同时执行
 * 那么就需要用到多线程的技术，一个线程接收，一个线程发送
 * 
 */

/**
 *
 * ChatDemo.java
 * @author wangbiao<br/>
 *         email:785497344@qq.com
 * @description 聊天程序的服务端
 * @since 1.0.0
 * @date 2013-7-6下午1:09:52
 *
 */
public class ChatDemo {
	public static void main(String[] args) {
		DatagramSocket send = null;
		DatagramSocket receive = null;
		try {
			send = new DatagramSocket();
			receive = new DatagramSocket(1000);
			new Thread(new Send(send)).start();
			new Thread(new Receive(receive)).start();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
}

/**
 *
 * @author wangbiao<br/>
 *         email:785497344@qq.com
 * @description 发送端
 * @since 1.0.0
 * @date 2013-7-6下午1:13:47
 *
 */
class Send implements Runnable {

	private DatagramSocket ds;

	public Send(DatagramSocket ds) {
		super();
		this.ds = ds;
	}

	@Override
	public void run() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = null;
		try {
			while ((line = br.readLine()) != null) {
				if ("886".equals(line)) {
					break;
				}
				byte[] buf = line.getBytes();
				DatagramPacket dp = new DatagramPacket(buf, buf.length,
						InetAddress.getByName("127.0.0.1"), 10000);
				ds.send(dp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

/**
 *
 * @author wangbiao<br/>
 *         email:785497344@qq.com
 * @description 接收端
 * @since 1.0.0
 * @date 2013-7-6下午1:14:18
 *
 */
class Receive implements Runnable {

	private DatagramSocket ds;

	public Receive(DatagramSocket ds) {
		super();
		this.ds = ds;
	}

	@Override
	public void run() {
		while (true) {
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf, buf.length);
			try {
				ds.receive(dp);
				String ip = dp.getAddress().getHostAddress();
				String data = new String(dp.getData(), 0, dp.getLength());
				System.out.println(ip + "::" + data);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}